<template>
  <t-form
    ref="form"
    :class="['item-container', `login-${type}`]"
    :data="formData"
    :rules="FORM_RULES"
    label-width="0"
    @submit="onSubmit"
  >
    <t-form-item name="username">
      <t-input v-model="formData.username" size="large" placeholder="请输入账号">
        <template #prefix-icon>
          <t-icon name="user" />
        </template>
      </t-input>
    </t-form-item>

    <t-form-item name="password">
      <t-input
        v-model="formData.password"
        size="large"
        :type="showPsw ? 'text' : 'password'"
        clearable
        placeholder="请输入登录密码"
      >
        <template #prefix-icon>
          <t-icon name="lock-on" />
        </template>
        <template #suffix-icon>
          <t-icon :name="showPsw ? 'browse' : 'browse-off'" @click="showPsw = !showPsw" />
        </template>
      </t-input>
    </t-form-item>

    <div class="check-container remember-pwd">
      <t-checkbox>记住账号</t-checkbox>
      <span class="tip" @click="$emit('forgot-password')">忘记账号？</span>
    </div>

    <t-form-item class="btn-container">
      <t-button block size="large" type="submit"> 登录 </t-button>
    </t-form-item>
  </t-form>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { login } from '@/api/user/index';
import { useRouter } from 'vue-router';
import {MessagePlugin} from "tdesign-vue-next";

/**
 * 当前表单类型（暂未用到，可扩展）
 */
const type = ref('default');

/**
 * 登录表单校验规则
 */
const FORM_RULES = {
  username: [{ required: true, message: '账号必填', type: 'error' }],
  password: [{ required: true, message: '密码必填', type: 'error' }],
};

/**
 * 登录表单ref
 */
const form = ref();
/**
 * 登录表单数据
 */
const formData = ref({
  username: '',
  password: '',
});

/**
 * 是否显示密码明文
 */
const showPsw = ref(false);

const router = useRouter();

/**
 * 登录表单提交
 */
const onSubmit = async () => {
  if (!formData.value.username || !formData.value.password) {
    await MessagePlugin.error('请填写账号和密码');
    return;
  }

  try {
    // 日志：打印登录参数
    console.log('[登录请求参数]', formData.value);
    const res = await login(formData.value);
    // 日志：打印登录响应
    console.log('登录响应', res.data);
    const result = res.data;
    if (result && result.code === 200 && result.data && result.data.token) {
      localStorage.setItem('token', result.data.token);
      localStorage.setItem('userInfo', JSON.stringify(result.data));
      localStorage.setItem('tokenTime', Date.now().toString());
      await MessagePlugin.success('登录成功');
      await router.push('/');
      window.location.reload();
    } else {
      await MessagePlugin.error(result?.message || '登录失败,请检查账号密码是否正确');
    }
  } catch (error) {
    // 日志：打印异常信息
    console.error('[登录失败]', error);
    await MessagePlugin.error('登录异常，请稍后重试');
  }
};
</script>

<style lang="less" scoped>
@import url('../login.less');
</style>
